﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ignitron.EEngine.Model;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace Ignitron.EEngine.Adapters.OpenGL
{
    /// <summary>
    /// Class representing OpenTK Model 
    /// </summary>
    internal class OpenTKModel: EModel
    {
        /// <summary>
        /// Alpha blending value
        /// </summary>
        private float mAlphaOpacity;

        /// <summary>
        /// Factory method for creating the OpenTK mesh
        /// </summary>
        protected override EMesh CreateMesh()
        {
            return new OpenTKMesh();
        }

        /// <summary>
        /// Sets the blending value
        /// </summary>
        internal void SetAlphaOpacity(float alpha)
        {
            mAlphaOpacity = alpha;
        }

        /// <summary>
        /// Rendering method
        /// </summary>
        internal void Render()
        {
            // set alpha rendering
            if (Math.Abs(mAlphaOpacity - 0.999f) < 0.001f)
            {
                GL.Disable(EnableCap.Blend);
                GL.Disable(EnableCap.ColorMaterial);
            }
            else
            {
                GL.Enable(EnableCap.Blend);
                GL.BlendEquationSeparate(BlendEquationMode.FuncAdd, BlendEquationMode.FuncAdd);
                GL.BlendFuncSeparate(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha, BlendingFactorSrc.One, BlendingFactorDest.Zero);
                GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.AmbientAndDiffuse);
                GL.Enable(EnableCap.ColorMaterial);
                GL.Color4(1f, 1f, 1f, mAlphaOpacity);
            }

            foreach (EMesh mesh in mMeshes)
            {
                (mesh as OpenTKMesh).Render();
            }

            GL.Disable(EnableCap.Blend);
            GL.Disable(EnableCap.ColorMaterial);
        }

        /// <summary>
        /// Method for rendering normal vectors
        /// </summary>
        internal void RenderNormals(Vector4 color, float magnitude)
        {
            foreach (EMesh mesh in mMeshes)
            {
                (mesh as OpenTKMesh).RenderNormals(color, magnitude);
            }
        }
    }
}
